<style rel="stylesheet/scss" lang="scss">
.context-row {
  min-height: 600px;
  max-height: 900px;
}
.height-inherit {
  height: inherit;
}
.menu-border-left {
  border-right: unset;
}
.context-right-border {
  border: 1px solid #e6eef7;
  border-left: unset;
}
.top-5 {
  top: 5px;
}
td .el-input-number {
  max-width: 80px;
}
.el-menu-item i {
  color: unset;
}
.el-menu-item.is-active {
  color: #fff !important;
  background-color: #28a087 !important;
}
.el-menu-item:hover {
  color: #fff !important;
  background-color: #28a087 !important;
  i {
    color: #fff !important;
  }
}
.height-36 {
  height: 36px;
}
.toolbar {
  min-height: 80px;
  border: 1px solid #e6eef7;
  border-bottom: unset;
  padding: 0 20px 0 20px;
}
.charge-sel {
  width: 260px;
}
</style>
<template>
  <el-row
    type="flex"
    class="p-20 context-row bg-white"
    justify="space-around">
    <el-col :span="24">
      <el-row
        type="flex"
        class="toolbar"
        align="middle">
        <el-col :span="1">
          <label>选择：</label>
        </el-col>
        <el-col
          :span="3"
          class="pr-10">
          <el-select
            v-model="query.categoryId"
            filterable
            placeholder="请选择品类"
            @change="changeCategory">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
        </el-col>
        <el-col
          :span="4"
          class="pr-10">
          <el-button
            :loading="importSubsidyLoading"
            type="warning"
            @click="importCommonPrice">导入品类基准价签</el-button>
        </el-col>
        <el-col
          :span="3"
          class="pr-10">
          <el-select
            v-model="copyId"
            filterable
            placeholder="请选择合作商">
            <el-option
              v-for="item in partnerOptions"
              :key="item.partnerCompanyId"
              :label="item.partnerCompanyName"
              :value="item.partnerCompanyId" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button
            type="warning"
            @click="copyPriceTag">复制价签</el-button>
        </el-col>
        <el-col
          :span="10"
          class="text-right">
          <el-button
            type="primary"
            @click="maintainPriceTag">上游价签维护</el-button>
        </el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-around">
        <el-col :span="2">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo full-height menu-border-left"
            background-color="#e6eef7"
            text-color="#494f54"
            active-text-color="#26A087">
            <el-menu-item
              index="安装"
              @click="changeMenu('安装')">
              <i class="icon-commonyuanquyunwei" />
              <span slot="title">安装</span>
            </el-menu-item>
            <el-menu-item
              index="维修"
              @click="changeMenu('维修')">
              <i class="icon-commonicon_shezhi" />
              <span slot="title">维修</span>
            </el-menu-item>
            <el-menu-item
              index="清洗"
              @click="changeMenu('清洗')">
              <i class="icon-commonshuibiao" />
              <span slot="title">清洗</span>
            </el-menu-item>
            <el-menu-item
              index="移机"
              @click="changeMenu('移机')">
              <i class="icon-commonhuowudui1" />
              <span slot="title">移机</span>
            </el-menu-item>
            <el-menu-item
              index="保养"
              @click="changeMenu('保养')">
              <i class="icon-commontuoguan" />
              <span slot="title">保养</span>
            </el-menu-item>
          </el-menu>
        </el-col>
        <el-col
          :span="14"
          class="context-right-border p-20">
          <el-row
            type="flex"
            align="middle">
            <el-col :span="12">
              <label>【{{ query.orderServiceType }}】的下游价签</label>
            </el-col>

            <el-col
              :span="8"
              class="text-right">
              <el-button
                type="primary"
                @click="addSubsidyPrice">添加价签</el-button>
            </el-col>
            <el-col
              :span="4"
              class="text-right">
              <el-button
                type="primary"
                @click="saveSubsidyPriceList">保存价签</el-button>
            </el-col>
          </el-row>
          <el-row
            type="flex"
            align="middle"
            class="pt-10">
            <el-col :span="24">
              <el-table
                ref="subsidyTable"
                :data="subsidyTableData"
                highlight-current-row
                class="full-width"
                empty-text="暂无数据"
                height="670"
                @current-change="subsidyCurrentChange">
                <el-table-column
                  width="300"
                  label="规格">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.serviceChargeId"
                      class="charge-sel"
                      filterable
                      placeholder="选择规格"
                      @change="changeCharge(scope.$index,scope.row)">
                      <el-option
                        v-for="item in priceOptions"
                        :key="item.serviceChargeId"
                        :label="item.specificationName +'--'+ item.measureTypeName"
                        :value="item.serviceChargeId">
                        <span style="float: left">{{ item.specificationName }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.measureTypeName }}</span>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="基准价格">
                  <template slot-scope="scope">
                    <span>￥{{ scope.row.inGuaranteeCommission?(scope.row.inGuaranteeCommission).toFixed(2):"" }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="补贴金额"
                  width="180">
                  <template slot-scope="scope">
                    <el-input-number
                      :precision="2"
                      :controls="false"
                      :min="-99999999.99"
                      :max="99999999.99"
                      v-model="scope.row.orderSubsidyPrice"
                      size="small"
                      placeholder="请输入金额" />
                  </template>
                </el-table-column>
                <el-table-column label="实结金额">
                  <template slot-scope="scope">
                    <span>￥{{ (scope.row.inGuaranteeCommission+(scope.row.orderSubsidyPrice?scope.row.orderSubsidyPrice:0)).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  label="操作">
                  <template slot-scope="scope">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="删除补贴"
                      placement="left">
                      <el-button
                        type="danger"
                        size="small"
                        icon="icon-commonshanchu"
                        circle
                        @click="removeSubsidy(scope.$index,scope.row)" />
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="关联上游"
                      placement="right">
                      <el-button
                        type="primary"
                        size="small"
                        icon="icon-commonguanlianshebei"
                        circle
                        @click="relatedPriceTag(scope.row)" />
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-col>
        <el-col
          :span="8"
          class="context-right-border p-20">
          <el-row
            type="flex"
            align="middle"
            class="height-36">
            <el-col :span="14">
              <label>【{{ subsidyCurrentRow?subsidyCurrentRow.specificationName:"--" }}】对应的上游价签盈利分析</label>
            </el-col>
            <el-col
              :span="10"
              class="text-right">
              <el-tooltip placement="left">
                <div slot="content">保存价签后生效</div>
                <el-button
                  type="warning"
                  @click="disassociate">取消关联</el-button>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row
            type="flex"
            align="middle"
            class="pt-10">
            <el-col :span="24">
              <el-table
                ref="masterInfoTable"
                :data="masterInfoTableData"
                empty-text="暂无数据"
                height="670"
                style="width: 100%"
                @row-dblclick="masterInfoRow2Click"
                @selection-change="disMasterPrice">
                <el-table-column
                  width="280"
                  label="服务名称">
                  <template slot-scope="info">
                    <span>{{ info.row.maintenanceServiceName?info.row.maintenanceServiceName:"--" }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  width="100"
                  label="上游结算">
                  <template slot-scope="info">
                    <span>￥{{ info.row.partnerSettlePrice?(info.row.partnerSettlePrice).toFixed(2):"" }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="盈亏分析">
                  <template slot-scope="info">
                    <span>￥{{ ((info.row.partnerSettlePrice?info.row.partnerSettlePrice:0)-((subsidyCurrentRow.inGuaranteeCommission?subsidyCurrentRow.inGuaranteeCommission:0)+(subsidyCurrentRow.orderSubsidyPrice?subsidyCurrentRow.orderSubsidyPrice:0))).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column type="selection" />
              </el-table>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!-- 设置上游价签 -->
      <el-dialog
        :fullscreen="true"
        :visible.sync="maintainPriceVisible"
        title="合作商上游价签维护">
        <el-row>
          <el-col :span="4">
            <el-select
              v-model="master.categoryId"
              filterable
              placeholder="请选择品类"
              @change="changeCategory">
              <el-option
                v-for="item in categoryOptions"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="master.orderServiceType"
              filterable
              placeholder="请选择服务类型"
              @change="changeServiceType">
              <el-option
                label="安装"
                value="安装" />
              <el-option
                label="维修"
                value="维修" />
              <el-option
                label="清洗"
                value="清洗" />
              <el-option
                label="拆机"
                value="拆机" />
              <el-option
                label="保养"
                value="保养" />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              class="ml-10"
              @click="addMasterPrice">添加上游价签</el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              @click="savePriceTagList">保存上游价签</el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              :loading="downloadLoading"
              type="primary"
              class="ml-10"
              @click="downloadModel">下载导入模板</el-button>
          </el-col>
          <el-col :span="3">
            <el-upload
              ref="uploadMaster"
              :action="importMasterUrl"
              :before-upload="beforeImportMaster"
              :on-success="successImportMaster"
              :on-error="errorImportMaster"
              :show-file-list="false"
              :disabled="importMasterLoading"
              :data="query"
              name="masterPrice">
              <el-button
                :loading="importMasterLoading"
                type="warning"
                class="ml-10">导入上游价签</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-table
          :data="partnerPriceData"
          height="627">
          <el-table-column
            width="180"
            label="服务品类">
            <template slot-scope="price">{{ price.row.categoryName }}</template>
          </el-table-column>
          <el-table-column
            width="180"
            label="服务类型">
            <template slot-scope="price">{{ price.row.orderServiceType?price.row.orderServiceType:"--" }}</template>
          </el-table-column>
          <el-table-column
            width="280"
            label="服务名称">
            <template slot-scope="price">
              <el-input
                v-model="price.row.maintenanceServiceName"
                placeholder="输入服务名称"
                size="small"
                clearable />
            </template>
          </el-table-column>
          <el-table-column
            width="160"
            label="结算价格">
            <template slot-scope="price">
              <el-input-number
                :precision="2"
                :controls="false"
                :min="0"
                :max="99999999.99"
                v-model="price.row.partnerSettlePrice"
                size="small"
                label="￥"
                placeholder="请输入金额" />
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作">
            <template slot-scope="price">
              <el-tooltip
                class="item"
                effect="dark"
                content="删除价签"
                placement="left">
                <el-button
                  type="danger"
                  size="small"
                  icon="icon-commonshanchu"
                  circle
                  @click="removePriceTag(price.$index,price.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- 关联上游 -->
      <el-dialog
        :title="relatedTitle"
        :visible.sync="relatedPriceVisible"
        width="40%">
        <el-row>
          <el-col :span="8">
            <el-input
              v-model="relatedKeyword"
              placeholder="请输入关键字搜索"
              clearable />
          </el-col>
          <el-col :span="4">
            <el-button
              type="primary"
              class="ml-10"
              @click="loadRelatedPriceTable">搜索</el-button>
          </el-col>
        </el-row>
        <el-table
          ref="relatedPriceTable"
          :data="relatedPriceData"
          tooltip-effect="dark"
          style="width: 100%"
          height="380"
          @row-dblclick="priceTableRow2Click"
          @selection-change="priceSelectionChange">
          <el-table-column type="selection" />
          <el-table-column
            width="120"
            label="服务品类">
            <template slot-scope="related">{{ related.row.categoryName }}</template>
          </el-table-column>
          <el-table-column
            width="120"
            label="服务类型">
            <template slot-scope="related">{{ related.row.orderServiceType?related.row.orderServiceType:"--" }}</template>
          </el-table-column>
          <el-table-column label="服务名称">
            <template slot-scope="related">{{ related.row.maintenanceServiceName?related.row.maintenanceServiceName:"--" }}</template>
          </el-table-column>
          <el-table-column label="结算价格">
            <template slot-scope="related">￥{{ related.row.partnerSettlePrice?related.row.partnerSettlePrice:"--" }}</template>
          </el-table-column>
        </el-table>
        <div
          slot="footer"
          class="dialog-footer">
          <el-button @click="relatedPriceVisible = false">取 消</el-button>
          <el-tooltip placement="top-end">
            <div slot="content">保存价签后生效</div>
            <el-button
              type="primary"
              @click="setMaster2Subsidy">确 定</el-button>
          </el-tooltip>
        </div>
      </el-dialog>
    </el-col>
  </el-row>
</template>

<script>
import { listPartnerOptions } from '@/api/common'
import { listPartnerCategory } from '@/api/category'
import { getToken } from '@/utils/auth'

import {
  getPartnerSubsidyPrice,
  saveSubsidyList,
  importPartnerSubsidyPrice,
  copyPartnerSubsidyPrice,
  removePartnerSubsidyPrice
} from '@/api/partnerSubsidyPrice'
import {
  getPartnerMasterPrice,
  getPartnerMasterPriceBySubsidy,
  saveList,
  getChargeList,
  savePartnerMasterPrice,
  removePartnerMasterPrice
} from '@/api/partnerMasterPrice'
export default {
  data() {
    return {
      tableKey: 1,
      query: {
        partnerId: '',
        categoryId: '',
        measureTypeId: '',
        specificationId: '',
        orderServiceType: '安装'
      },
      master: {
        partnerId: '',
        categoryId: '',
        orderServiceType: '安装'
      },
      copyId: '',
      activeMenu: '安装',
      serviceChargeId: 527,
      relatedTitle: '',
      importMasterUrl:
        '/wxh-cloud-rest/rest/' + getToken() + '/partner/priceTag/import',
      importSubsidyLoading: false,
      importMasterLoading: false,
      maintainPriceVisible: false,
      relatedPriceVisible: false,
      partnerPriceData: [],
      relatedPriceData: [],
      selectedPrice: [],
      selectedDisPrice: [],
      relatedKeyword: '',
      category: {},
      specification: {},
      measureType: {},
      priceOptions: [],
      categoryOptions: [],
      partnerOptions: [],
      masterPriceFrom: {
        masterPriceId: '',
        partnerId: '',
        categoryId: '',
        maintenanceServiceName: '',
        partnerSettlePrice: '',
        orderSubsidyPricce: '',
        serviceChargeId: ''
      },
      subsidyTableData: [],
      subsidyCurrentRow: {},
      masterInfoTableData: [],
      tableData: [],
      allowanceData: [],
      FromList: {
        newData: '',
        editData: ''
      },
      downloadLoading: false,
      bookType: 'xlsx',
      filename: '上游价签导入模板'
    }
  },
  computed: {},
  watch: {},
  created() {
    const self = this
    self.query.partnerId = self.$route.query.partnerId
    self.master.partnerId = self.$route.query.partnerId
    self.loadPartnerOptions()
    self.loadCategoryOptions()
  },
  methods: {
    downloadModel() {
      this.downloadLoading = true
      const filename = this.filename + new Date().getTime()
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '合作商名称',
          '品类名称',
          '服务类型',
          '结算名称',
          '结算金额'
        ]
        const data = []
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: filename,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    setMaster2Subsidy() {
      const self = this
      let masterPriceId = ''
      let ids = []
      if (self.subsidyCurrentRow && self.subsidyCurrentRow.masterPriceId) {
        ids = self.subsidyCurrentRow.masterPriceId.split(',')
      }
      if (self.selectedPrice && self.selectedPrice.length > 0) {
        for (var price in self.selectedPrice) {
          ids.push(self.selectedPrice[price].masterPriceId + '')
        }
        var len = ids.length
        if (len > 0) {
          ids = Array.from(new Set(ids))
          len = ids.length
          ids.forEach(id => {
            masterPriceId += id + ','
          })
          masterPriceId = masterPriceId.substring(0, masterPriceId.length - 1)
          self.subsidyCurrentRow.masterPriceId = masterPriceId
          self.loadMasterPriceBySubsidy()
          self.$refs.masterInfoTable.clearSelection()
        }
      }
      self.relatedPriceVisible = false
    },
    priceTableRow2Click(row) {
      this.$refs.relatedPriceTable.toggleRowSelection(row)
    },
    disassociate() {
      // 取消关联 保存价签生效
      const self = this
      let masterPriceId = ''
      if (
        self.selectedDisPrice &&
        self.selectedDisPrice.length > 0 &&
        self.subsidyCurrentRow &&
        self.subsidyCurrentRow.masterPriceId
      ) {
        const ids = self.subsidyCurrentRow.masterPriceId.split(',')
        var len = ids.length
        self.selectedDisPrice.forEach(price => {
          for (var i = 0; i < len; i++) {
            if (parseInt(ids[i]) === price.masterPriceId) {
              ids.splice(i, 1)
            }
          }
        })
        if (ids && ids.length > 0) {
          ids.forEach(id => {
            masterPriceId += id + ','
          })
          self.subsidyCurrentRow.masterPriceId = masterPriceId.substring(
            0,
            masterPriceId.length - 1
          )
        } else {
          self.subsidyCurrentRow.masterPriceId = ''
        }
        self.loadMasterPriceBySubsidy()
        self.$refs.masterInfoTable.clearSelection()
      }
    },
    disMasterPrice(val) {
      this.selectedDisPrice = val
    },
    masterInfoRow2Click(row) {
      this.$refs.masterInfoTable.toggleRowSelection(row)
    },
    importCommonPrice() {
      // 导入品类基准价签
      const self = this
      if (!self.query.categoryId) {
        self.$message.info('请选择品类！')
        return
      }
      if (self.subsidyTableData && self.subsidyTableData.length > 0) {
        self.$message.info('补贴价签为空才能导入，请先清空补贴价签再导入！')
        return
      }
      self
        .$confirm('导入品类基准价签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          self.importSubsidyLoading = true
          importPartnerSubsidyPrice(self.query)
            .then(response => {
              if (response.data.status === 'success') {
                self.loadSubsidyTable()
                self.$message({
                  message: '导入完成',
                  type: 'success'
                })
              } else {
                self.$message({
                  message: '导入失败' + response.data.messge,
                  type: 'warning'
                })
              }
              self.importSubsidyLoading = false
            })
            .catch(() => {
              self.$message({
                type: 'info',
                message: '网络请求失败'
              })
              self.importSubsidyLoading = false
            })
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '你取消了导入！'
          })
        })
    },
    beforeImportMaster(file) {
      // 导入合作商上游价签
      const self = this
      const isXLS = file.type === 'application/vnd.ms-excel'
      const isXLSX =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isNameEqXlsOrXlsx = /\.(xlsx|xls|XLSX|XLS)$/.test(file.name)
      if ((!isXLS || !isXLSX) && !isNameEqXlsOrXlsx) {
        self.$message.error('导入文件只能是 XLS 或者 XLSX 格式!')
        return false
      } else {
        self.importMasterLoading = true
      }

      return (isXLS || isXLSX) && isNameEqXlsOrXlsx
    },
    successImportMaster(res, file) {
      // 导入合作商上游价签成功
      const self = this
      self.importMasterLoading = false
      self.$refs.uploadMaster.clearFiles()
      self.loadMasterTable()
      if (res.status === 'success') {
        this.$notify({
          title: '导入结果',
          dangerouslyUseHTMLString: true,
          message: '<strong>' + res.data.message + '</strong>',
          type: 'success',
          duration: 0
        })
      } else {
        this.$notify({
          title: '导入结果',
          dangerouslyUseHTMLString: true,
          message: '<strong>' + res.messge + '</strong>',
          type: 'warning'
        })
      }
    },
    errorImportMaster(err, file, fileList) {
      // 复制合作商上游价签失败
      self.importMasterLoading = false
      const self = this
      this.$notify({
        title: '导入失败',
        dangerouslyUseHTMLString: true,
        message: '<strong>' + err + '</strong>',
        type: 'warning',
        duration: 0
      })
    },
    relatedPriceTag() {
      // 关联上游价签
      var self = this
      self.loadRelatedPriceTable()
      self.relatedPriceVisible = true
      self.selectedPrice = []
      if (self.$refs.relatedPriceTable) {
        self.$refs.relatedPriceTable.clearSelection()
      }
      self.relatedTitle =
        '选择【' +
        (self.subsidyCurrentRow
          ? self.subsidyCurrentRow.specificationName
          : '--') +
        '】对应上游的价签'
    },
    maintainPriceTag() {
      // 上游价签维护
      var self = this
      self.loadMasterTable()
      self.maintainPriceVisible = true
      self.master.partnerId = self.query.partnerId
      self.master.categoryId = self.query.categoryId
      self.master.orderServiceType = self.query.orderServiceType
    },
    priceSelectionChange(val) {
      this.selectedPrice = val
    },
    forceRefreshTable() {
      this.tableKey = this.tableKey + 1
    },
    cleanQuery() {
      this.query = {
        partnerId: this.query.partnerId,
        categoryId: '',
        measureTypeId: '',
        specificationId: '',
        orderServiceType: this.query.orderServiceType
      }
    },
    cleanFrom() {
      this.masterPriceFrom = {
        masterPriceId: '',
        partnerId: '',
        categoryId: '',
        maintenanceServiceName: '',
        partnerSettlePrice: '',
        orderSubsidyPricce: '',
        serviceChargeId: ''
      }
    },
    changeMenu(menu) {
      var self = this
      self.query.orderServiceType = menu
      if (!self.query.categoryId) {
        self.$message({
          message: '请先选择品类!',
          type: 'info'
        })
      }
      self.loadPriceOptions()
      self.subsidyCurrentRow = {}
      self.loadSubsidyTable()
      self.forceRefreshTable()
    },
    loadCategoryOptions() {
      var self = this
      self.categoryOptions = []
      var data = { partnerId: self.query.partnerId }
      listPartnerCategory(data)
        .then(response => {
          if (response.data.status === 'success') {
            self.categoryOptions = response.data.data
            if (self.categoryOptions && self.categoryOptions.length > 0) {
              self.query.categoryId = self.categoryOptions[0].categoryId
              self.loadPriceOptions()
              self.subsidyCurrentRow = {}
              self.loadSubsidyTable()
            } else {
              self.query.categoryId = ''
              self.$message({
                message: '品类列表为空，请先添加品类!',
                type: 'warning'
              })
            }
          } else {
            self.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    loadPartnerOptions() {
      var self = this
      self.partnerOptions = []
      var data = {}
      listPartnerOptions(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.partnerOptions = response.data.data
          } else {
            this.$message({
              message: '合作商加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    loadPriceOptions() {
      var self = this
      getChargeList(self.query)
        .then(response => {
          if (response.data.status === 'success') {
            if (response.data.data && response.data.data.length !== 0) {
              self.priceOptions = response.data.data
            } else {
              this.$message({
                message: '规格没有对应的基准价签，请先添加基准价签!',
                type: 'warning'
              })
            }
          } else {
            this.$message({
              message: '基准价签加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    loadSubsidyTable() {
      if (this.query.partnerId && this.query.orderServiceType) {
        getPartnerSubsidyPrice(this.query)
          .then(response => {
            if (response.data.status === 'success') {
              this.subsidyTableData = response.data.data
              if (this.subsidyTableData && this.subsidyTableData.length > 0) {
                this.$refs.subsidyTable.setCurrentRow(this.subsidyTableData[0])
              } else {
                this.masterInfoTableData = []
              }
            } else {
              this.subsidyTableData = []
              this.masterInfoTableData = []
              this.$message({
                message: '补贴价签加载失败' + response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.subsidyTableData = []
            this.masterInfoTableData = []
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
      } else {
        this.subsidyTableData = []
      }
    },
    subsidyCurrentChange(val) {
      this.subsidyCurrentRow = val
      this.loadMasterPriceBySubsidy()
    },
    loadMasterPriceBySubsidy() {
      if (this.subsidyCurrentRow) {
        getPartnerMasterPriceBySubsidy(this.subsidyCurrentRow)
          .then(response => {
            if (response.data.status === 'success') {
              this.masterInfoTableData = response.data.data
            } else {
              this.masterInfoTableData = []
              this.$message({
                message: '下游价签加载失败' + response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.masterInfoTableData = []
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
      } else {
        this.masterInfoTableData = []
      }
    },
    loadMasterTable() {
      if (this.master.partnerId && this.master.orderServiceType) {
        getPartnerMasterPrice(this.master)
          .then(response => {
            if (response.data.status === 'success') {
              this.partnerPriceData = response.data.data
            } else {
              this.partnerPriceData = []
              this.$message({
                message: '服务价签加载失败' + response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.partnerPriceData = []
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
      } else {
        this.partnerPriceData = []
      }
    },
    loadRelatedPriceTable() {
      if (
        this.query.partnerId &&
        this.query.categoryId &&
        this.query.orderServiceType
      ) {
        const param = {
          keyword: this.relatedKeyword,
          partnerId: this.query.partnerId,
          categoryId: this.query.categoryId,
          orderServiceType: this.query.orderServiceType
        }
        getPartnerMasterPrice(param)
          .then(response => {
            if (response.data.status === 'success') {
              this.relatedPriceData = response.data.data
            } else {
              this.relatedPriceData = []
              this.$message({
                message: '服务价签加载失败' + response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.relatedPriceData = []
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
      } else {
        this.relatedPriceData = []
      }
    },
    changeCategory(value) {
      if (value) {
        this.subsidyCurrentRow = {}
        this.loadSubsidyTable()
        this.loadMasterTable()
        this.loadPriceOptions()
        let obj = {}
        obj = this.categoryOptions.find(item => {
          return item.categoryId === value
        })
        if (obj && typeof obj !== 'undefined') {
          this.category = obj
        }
      }
    },
    changeServiceType(value) {
      if (value) {
        this.loadMasterTable()
      }
    },
    copyPriceTag() {
      var self = this
      if (self.subsidyTableData && self.subsidyTableData.length > 0) {
        self.$message.info('补贴价签为空才能复制，请先清空补贴价签再复制！')
        return false
      }
      if (self.copyId && self.query.partnerId) {
        copyPartnerSubsidyPrice({
          copyId: self.copyId,
          partnerCompanyId: self.query.partnerId
        })
          .then(response => {
            if (response.data.status === 'success') {
              this.loadSubsidyTable()
              this.$message({
                message: '合作商价签复制成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: '合作商价签复制失败,' + response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
      } else {
        self.$message({
          type: 'warning',
          message: '请选择合作商'
        })
      }
    },
    addSubsidyPrice() {
      var self = this
      if (self.query.categoryId) {
        self.subsidyTableData.unshift({
          subsidyPriceId: null,
          partnerCompanyId: self.query.partnerId,
          categoryId: self.query.categoryId,
          categoryName: self.category.name,
          maintenanceServiceName: '',
          inGuaranteeCommission: null,
          serviceChargeId: '',
          masterPriceId: null,
          measureTypeId: null,
          measureTypeName: '',
          specificationId: null,
          specificationName: ''
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择品类'
        })
      }
    },
    addMasterPrice() {
      var self = this
      if (!self.master.categoryId) {
        this.$message({
          type: 'warning',
          message: '请选择品类'
        })
        return
      }
      if (!self.master.orderServiceType) {
        this.$message({
          type: 'warning',
          message: '请选择服务类型'
        })
        return
      }
      let obj = {}
      obj = self.categoryOptions.find(item => {
        return item.categoryId === self.master.categoryId
      })
      self.partnerPriceData.unshift({
        masterPriceId: null,
        partnerCompanyId: self.master.partnerId,
        categoryId: self.master.categoryId,
        categoryName: obj.categoryName,
        orderServiceType: self.master.orderServiceType,
        maintenanceServiceName: '',
        partnerSettlePrice: 0.0,
        orderSubsidyPricce: 0.0,
        inGuaranteeCommission: null,
        serviceChargeId: '',
        measureTypeId: null,
        measureTypeName: '',
        specificationId: null,
        specificationName: ''
      })
    },
    changeCharge(index, row) {
      var self = this
      let obj = {}
      obj = self.priceOptions.find(item => {
        return item.serviceChargeId === row.serviceChargeId
      })
      if (obj && typeof obj !== 'undefined') {
        let repeatSubsidy = {}
        repeatSubsidy = self.subsidyTableData.find(item => {
          return (
            item.serviceChargeId === row.serviceChargeId &&
            item.specificationId &&
            item.measureTypeId
          )
        })
        if (repeatSubsidy && typeof repeatSubsidy !== 'undefined') {
          row.serviceChargeId = ''
          self.$message.info(
            '已经存在对应的上游价签：' +
              obj.specificationName +
              '--' +
              obj.measureTypeName +
              '，请选择其他规格！'
          )
          return
        }
        self.subsidyTableData[index].inGuaranteeCommission =
          obj.inGuaranteeCommission
        self.subsidyTableData[index].specificationId = obj.specificationId
        self.subsidyTableData[index].specificationName = obj.specificationName
        self.subsidyTableData[index].measureTypeId = obj.measureTypeId
        self.subsidyTableData[index].measureTypeName = obj.measureTypeName
      }
    },
    saveSubsidyPriceList() {
      // 保存所有补贴价签
      var self = this
      const newData = []
      const editData = []
      self.subsidyTableData.find(item => {
        if (item.subsidyPriceId) {
          editData.push(item)
        } else {
          newData.push(item)
        }
      })
      var list = []
      list.push.apply(list, newData)
      list.push.apply(list, editData)
      for (var i in list) {
        if (
          list[i].serviceChargeId === null ||
          list[i].serviceChargeId === ''
        ) {
          self.$message({
            message: '规格不能为空',
            type: 'warning'
          })
          return
        }
        if (
          list[i].orderSubsidyPrice === null ||
          typeof list[i].orderSubsidyPrice === 'undefined'
        ) {
          self.$message({
            message: '下游补贴价格不能为空',
            type: 'warning'
          })
          return
        }
      }
      if (
        (newData && newData.length > 0) ||
        (editData && editData.length > 0)
      ) {
        self
          .$confirm('保存补贴价签, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            self.FromList.newData = JSON.stringify(newData)
            self.FromList.editData = JSON.stringify(editData)
            var fromData = self.assemblesFromData(self.FromList)
            saveSubsidyList(fromData)
              .then(response => {
                if (response.data.status === 'success') {
                  self.loadSubsidyTable()
                  self.$message({
                    type: 'success',
                    message: '保存补贴价签成功!'
                  })
                } else {
                  self.$message({
                    message: '保存补贴价签失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                self.$message({
                  type: 'info',
                  message: '保存补贴价签失败'
                })
              })
          })
          .catch(() => {
            self.$message({
              type: 'info',
              message: '已取消保存'
            })
          })
      }
    },
    savePriceTagList(row, type) {
      // 保存多个价签---针对补贴，其他有需要批量添加的功能可以在改造一下这个方法就可以
      var self = this
      // 验证
      // 提示是否保存
      // 确定提交·
      // 取消跳过
      const newData = []
      const editData = []
      self.partnerPriceData.find(item => {
        if (item.masterPriceId) {
          editData.push(item)
        } else {
          newData.push(item)
        }
      })
      var list = []
      list.push.apply(list, newData)
      list.push.apply(list, editData)
      for (var i in list) {
        if (
          list[i].maintenanceServiceName === null ||
          list[i].maintenanceServiceName === ''
        ) {
          self.$message({
            message: '服务名称为空',
            type: 'warning'
          })
          return
        }
        if (
          list[i].partnerSettlePrice === null ||
          typeof list[i].partnerSettlePrice === 'undefined'
        ) {
          self.$message({
            message: '上游结算价格不能为空',
            type: 'warning'
          })
          return
        }
      }
      if (
        (newData && newData.length > 0) ||
        (editData && editData.length > 0)
      ) {
        self
          .$confirm('保存服务价签, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            self.FromList.newData = JSON.stringify(newData)
            self.FromList.editData = JSON.stringify(editData)
            var fromData = self.assemblesFromData(self.FromList)
            saveList(fromData)
              .then(response => {
                if (response.data.status === 'success') {
                  self.loadMasterTable()
                  self.$message({
                    type: 'success',
                    message: '保存服务价签成功!'
                  })
                } else {
                  self.$message({
                    message: '保存服务价签失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                self.$message({
                  type: 'info',
                  message: '保存服务价签失败'
                })
              })
          })
          .catch(() => {
            self.$message({
              type: 'info',
              message: '已取消保存'
            })
          })
      }
    },
    savePriceTag(row) {
      var self = this
      // 验证
      // 提示是否保存
      // 确定提交·
      // 取消跳过
      if (row) {
        if (
          row.maintenanceServiceName === null ||
          row.maintenanceServiceName === ''
        ) {
          self.$message({
            message: '服务名称为空',
            type: 'warning'
          })
          return
        }
        if (row.serviceChargeId === null || row.serviceChargeId === '') {
          self.$message({
            message: '请选择上游价签',
            type: 'warning'
          })
          return
        }
        if (
          row.partnerSettlePrice === null ||
          typeof row.partnerSettlePrice === 'undefined'
        ) {
          self.$message({
            message: '上游结算价格不能为空',
            type: 'warning'
          })
          return
        }
        if (
          row.orderSubsidyPricce === null ||
          typeof row.orderSubsidyPricce === 'undefined'
        ) {
          self.$message({
            message: '下游补贴价格不能为空',
            type: 'warning'
          })
          return
        }

        self
          .$confirm('保存服务价签, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            self.initPriceFrom(row)
            var fromData = self.assemblesFromData(self.masterPriceFrom)
            savePartnerMasterPrice(fromData)
              .then(response => {
                if (response.data.status === 'success') {
                  self.loadMasterTable()
                  self.$message({
                    type: 'success',
                    message: '保存服务价签成功!'
                  })
                } else {
                  self.$message({
                    message: '保存服务价签失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                self.$message({
                  type: 'info',
                  message: '保存服务价签失败'
                })
              })
          })
          .catch(() => {
            self.$message({
              type: 'info',
              message: '已取消保存'
            })
          })
      }
    },
    removeSubsidy(index, row) {
      var self = this
      if (row && row.subsidyPriceId) {
        var data = {
          subsidyPriceId: row.subsidyPriceId
        }
        this.$confirm('删除补贴价签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            removePartnerSubsidyPrice(data)
              .then(response => {
                if (response.data.status === 'success') {
                  self.subsidyTableData.splice(index, 1)
                  self.subsidyCurrentRow = {}
                  this.$message({
                    type: 'success',
                    message: '删除服务价签成功!'
                  })
                } else {
                  this.$message({
                    message: '删除服务价签失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '删除服务价签失败'
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        this.$confirm('删除服务价签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            self.subsidyTableData.splice(index, 1)
            self.subsidyCurrentRow = {}
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    removePriceTag(index, row) {
      var self = this
      if (row && row.masterPriceId) {
        var data = {
          masterPriceId: row.masterPriceId
        }
        this.$confirm('删除服务价签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            removePartnerMasterPrice(data)
              .then(response => {
                if (response.data.status === 'success') {
                  self.partnerPriceData.splice(index, 1)
                  self.allowanceData = this.arrayUnique(
                    self.partnerPriceData,
                    'serviceChargeId'
                  )
                  this.$message({
                    type: 'success',
                    message: '删除服务价签成功!'
                  })
                } else {
                  this.$message({
                    message: '删除服务价签失败' + response.data.messge,
                    type: 'warning'
                  })
                }
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '删除服务价签失败'
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        this.$confirm('删除服务价签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            self.partnerPriceData.splice(index, 1)
            self.allowanceData = this.arrayUnique(
              self.partnerPriceData,
              'serviceChargeId'
            )
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    arrayUnique(arr, name) {
      var hash = {}
      return arr.reduce(function(item, next) {
        hash[next[name]] ? '' : (hash[next[name]] = true && item.push(next))
        return item
      }, [])
    },
    initPriceFrom(row) {
      var self = this
      self.masterPriceFrom = {}
      self.masterPriceFrom.masterPriceId = row.masterPriceId
      self.masterPriceFrom.partnerCompanyId = row.partnerCompanyId
      self.masterPriceFrom.categoryId = row.categoryId
      self.masterPriceFrom.maintenanceServiceName = row.maintenanceServiceName
      self.masterPriceFrom.partnerSettlePrice = row.partnerSettlePrice
      self.masterPriceFrom.orderSubsidyPricce = row.orderSubsidyPricce
      self.masterPriceFrom.serviceChargeId = row.serviceChargeId
    },
    assemblesFromData(data) {
      var fromData = new FormData()
      if (data) {
        for (var prop in data) {
          if (data[prop] !== null) {
            fromData.append(prop, data[prop])
          } else {
            fromData.append(prop, '')
          }
        }
      }
      if (fromData) {
        return fromData
      } else {
        return new FormData()
      }
    }
  }
}
</script>
